<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Role extends Model
{
    //
    use  SoftDeletes;
    protected $table = 'roles';
    protected $fillable = ['name'];

    /**
     * 角色搜索
     * @param $query
     * @param $name
     */
    public function scopeName($query, $name)
    {
        if ($name) {
            $query->where('name', 'like', '%' . $name . '%');
        }
    }


    /**
     * 新增角色
     * @param $data
     * @param $menus
     * @return bool
     */
    static public function add($data, $menus)
    {
        try {

            $role = self::create($data);
            $role->menus()->createMany($menus);

            return true;
        } catch (\Exception $exception) {
            return false;

        }
    }

    /**
     * 关联角色菜单表
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function menus()
    {
        return $this->hasMany(RoleMenu::class, 'role_id');
    }

    /**
     * 编辑
     * @param $id
     * @param $name
     * @param $menus
     * @return bool
     */
   static public function edit($id, $name, $menus)
    {
        try {
            $re = self::find($id);
            $re->name = $name;
            $re->save();
            $re->menus()->delete();
            $re->menus()->createMany($menus);
            return true;
        }catch (\Exception $exception){
            return false;
        }
    }


}
